#include "TileMap.h"
#include "os/Graphics/Graphics.h"

using namespace leo;

TileMap::TileMap(char* _file)
{
	anacondaMap.ReadFile(_file);
	textura = Texture::Ptr(new  Texture);

	std::string kFilename( "../data/" + std::string(anacondaMap.szDefBitmapFile) );
	textura->SetFilename(kFilename);
	textura->SetHeight(anacondaMap.usBitmapHeight);
	textura->SetWidth(anacondaMap.usBitmapWidth);
}

TileMap::~TileMap(void)
{
}
void TileMap::SetPos(int _x, int _y)
{
	x = _x;
	y = _y;
}

void TileMap::Create(int _tileHorizontal, int _tileVertical)
{
	
	matriz = new unsigned int* [_tileHorizontal];


	for (int i=0; i < _tileHorizontal; i++)
	{
		matriz[i] = new unsigned int[_tileVertical];


		for (int j=0; j < _tileVertical; j++)
		{
			matriz[i][j] = anacondaMap.pbiBlock[(j*_tileHorizontal)+i].sTileNum;

			tiles[matriz[i][j]]->SetPos(x+(i*tiles[matriz[i][j]]->GetWidth()),y-(j*tiles[matriz[i][j]]->GetHeight()));
			Tile* tmp = new Tile(0,0,0,0,0,textura);
			*tmp = *tiles[matriz[i][j]];
			if(anacondaMap.pbiBlock[(j*_tileHorizontal)+i].ucFlags!=0)
			{
			tmp->SetCollisionable(true);
			}
			tileMatrix.push_back(tmp);


		}
	}

}

void TileMap::Draw(leo::Graphics *_graph)
{

	for(int i=0;i < width; i++)
	{
		for(int j=0; j < height;j++)
		{
			tileMatrix[(j*width)+i]->Draw(_graph);		

		}
	}

}

void TileMap::Update(float _timeBetweenFrames)
{
	for (int i=0;i < tiles.size();i++)
	{
	//	tiles[i]->Update(_timeBetweenFrames);
	}
}

void TileMap::SetTile(int _tile, int _x, int _y)
{
	matriz[_x][_y]=_tile;
	
}

void TileMap::AddTile(leo::Tile *_til)
{
	tiles.push_back(_til);
}

void TileMap::ConvertFromAnaconda(leo::Graphics *_graph)
{

	_graph->LoadTexture(textura);


	width =	anacondaMap.usTileCountX;
	height = anacondaMap.usTileCountY;

	anim = new AnimationInfo(1,1,1);

//-------creacion de tipos de tiles-------------------	
	int tilesY = (anacondaMap.usBitmapHeight/anacondaMap.usTileHeight);
	int tilesX = (anacondaMap.usBitmapWidth/anacondaMap.usTileWidth);
	
	vector<Tile*>::iterator iter;

	for(int j=0; j < tilesY;j++)
	{
		for(int i=0; i < tilesX;i++)
		{
		tmpTile = new Tile(0,0,anacondaMap.usTileWidth,anacondaMap.usTileHeight,anacondaMap.ulColorKey,textura);
		
		tmpTile->SetAnimationInfo(anim);
		tmpTile->SetTextureHeight(anacondaMap.usTileHeight);
		tmpTile->SetTextureWidth(anacondaMap.usTileWidth);

		tmpTile->SetFrame(i*anacondaMap.usTileWidth,j*anacondaMap.usTileHeight,anacondaMap.usTileWidth,anacondaMap.usTileHeight);

		iter = tiles.end();
		tiles.insert(iter,tmpTile);
		}

	}
//-----------end creacion de tipos de tile------------------

	this->Create(width,height);

}

void TileMap::SetCollisions(leo::CheckCollision* _col, int _n)
{

	for(int i=0; i < tileMatrix.size();i++)
		{
			if(tileMatrix[i]->GetCollisionable())
			_col->Register(tileMatrix[i],_n);
	

		}
}